package com.ukao.cashregister.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.jiangdg.usbcamera.UVCCameraHelper;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.Size;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.common.AbstractUVCCameraHandler;
import com.serenegiant.usb.widget.CameraViewInterface;
import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.CameraPhotoAdapter;
import com.ukao.cashregister.base.MvpActivity;
import com.ukao.cashregister.bean.ProductRelImgBean;
import com.ukao.cashregister.listener.OnItemChildClickListener;
import com.ukao.cashregister.pesenter.CameraPesenter;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.FileUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.UploadUtils;
import com.ukao.cashregister.view.CameraView;
import com.ukao.cashregister.widget.StateImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 商米商品录入拍照界面
 */
public class CameraSunMiActivity extends MvpActivity<CameraPesenter> implements CameraView, CameraDialog.CameraDialogParent, CameraViewInterface.Callback {
    @BindView(R.id.surfaceView)
    View surfaceView;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.finish_btn)
    StateImageView finishBtn;
    @BindView(R.id.img_camera)
    StateImageView imgCamera;
    private Context context;
    //屏幕宽高
    private int screenWidth;
    private int screenHeight;
    private String photoPath;
    private CameraPhotoAdapter mCameraPhotoAdapter;
    private SoundPool mSoundPool;
    private int outgoing;

    private UploadUtils mUploadUtils;
    private String orderProId;
    private ArrayList<ProductRelImgBean> mPhotoData;
    private  List  uploadData=new ArrayList();/*上传图片集合*/

    private UVCCameraHelper mCameraHelper;
    private CameraViewInterface mUVCCameraView;
    private boolean isRequest;
    private boolean isPreview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_sunmi);
        ButterKnife.bind(this);
        context = this;
        //獲取設備信息
        initView();
        initData();
        initListener();
        takeCamerPhotoSoundPool();
    }

    @Override
    protected CameraPesenter createPresenter() {
        return new CameraPesenter(this);
    }

    protected void initView() {
        orderProId=getIntent().getStringExtra(ARG_PARAM1);
        mPhotoData= (ArrayList<ProductRelImgBean>) getIntent().getSerializableExtra(ARG_PARAM2);

        mUVCCameraView = (CameraViewInterface) surfaceView;
        mUVCCameraView.setCallback(this);
        mCameraHelper = UVCCameraHelper.getInstance();
        mCameraHelper.setDefaultFrameFormat(UVCCameraHelper.FRAME_FORMAT_YUYV);
//        mCameraHelper.updateResolution(1280, 720);
        mCameraHelper.setDefaultPreviewSize(1280, 720);
        mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);
        mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
            @Override
            public void onPreviewResult(byte[] nv21Yuv) {

            }
        });

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCameraPhotoAdapter=new CameraPhotoAdapter(this,mPhotoData);
        recyclerView.setAdapter(mCameraPhotoAdapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mCameraPhotoAdapter.setOnItemChildClickListener(mOnItemChildClickListener);
    }


    private OnItemChildClickListener mOnItemChildClickListener=new OnItemChildClickListener() {
        @Override
        public void onChildItemClick(int id, int pos) {
            switch (id) {
                case R.id.image_remove:
                    ProductRelImgBean item = mCameraPhotoAdapter.getItem(pos);
                    mvpPresenter.deleteRelImg(item);
                    break;
            }
        }
    };

    public String getPhotoSavePath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/ukaoPOS/XKXPhoto/";
        } else {
            pathString = "/sdcard/ukaoPOS/XKXPhoto/";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }

    private void initData() {
        photoPath = getPhotoSavePath();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

    }


    @SuppressLint("NewApi")
    public   void  takeCamerPhotoSoundPool(){
        SoundPool.Builder builder = new SoundPool.Builder();
        //传入音频数量
        builder.setMaxStreams(2);
        //AudioAttributes是一个封装音频各种属性的方法
        AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
        //设置音频流的合适的属性
        attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
        //加载一个AudioAttributes
        builder.setAudioAttributes(attrBuilder.build());
        mSoundPool= builder.build();
        outgoing=mSoundPool.load(this, R.raw.success, 1);
    }

    private void showError() {
        T.show(getResources().getString(R.string.unconnected_camera));
    }

    /**
     * 清除相机数据
     */
    private void cleanCameraData( ) {
        try {
            L.i("清除数据时=");
            //system/app系统自带的应用程序，无法删除。
            // data/app用户程序安装的目录，有删除权限。安装时把apk文件复制到此目录。
            Process su = Runtime.getRuntime().exec("su");
            String cmd = "rm -r " + "/data/data/" +"com.android.camera2";
            cmd = cmd + "\n exit\n";
            //以下两句代表重启设备
            //cmd ="reboot";
            //cmd = cmd + "\n exit\n";
            su.getOutputStream().write(cmd.getBytes());
            if ((su.waitFor() != 0)) {

            }
        } catch (Exception e) {
            L.i("清除数据时=" + e.toString());
        }



    }
    @Override
    protected void onPause() {
        super.onPause();
        cleanCameraData();
    }

    /**
     * 压缩图片 Listener 方式
     */
    private void compressWithLs(final String photos) {
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }
                    @Override
                    public void onSuccess(File file) {
                        mPhotoData.add(0, new ProductRelImgBean(file.getPath()));
                        mCameraPhotoAdapter.setDatas(mPhotoData);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mPhotoData.add(0, new ProductRelImgBean(photos));
                        mCameraPhotoAdapter.setDatas(mPhotoData);

                    }
                }).launch();
    }

    public String getPath() {
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        String pathString = "";
        if (dcim.exists()) {
            pathString = dcim + "/ukaoPOS/compressImage/";
        } else {
            pathString = "/sdcard/ukaoPOS/compressImage/";
        }
        File videoPathFile = new File(pathString);
        if (!videoPathFile.exists()) {
            videoPathFile.mkdirs();
        }
        return pathString;
    }

    private int playCallSounds() {
        try {
            // 播放
            int id = mSoundPool.play(outgoing, // 声音资源
                    1.0f, // 左声道
                    1.0f, // 右声道
                    1, // 优先级，0最低
                    0, // 循环次数，0是不循环，-1是永远循环
                    1); // 回放速度，0.5-2.0之间。1为正常速度
            return id;
        } catch (Exception e) {
            return -1;
        }
    }

    @OnClick({R.id.finish_btn, R.id.img_camera,R.id.back_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_btn:
                uploadData.clear();
                for (ProductRelImgBean mImgBean : mPhotoData) {
                    if (CheckUtils.isHttp(mImgBean.getCameraImg())){
                        uploadData.add(mImgBean.getCameraImg());
                    }
                }
                if (CheckUtils.isEmpty(uploadData)){
                    int    photoCount=0;
                    for (ProductRelImgBean productRelImgBean : mCameraPhotoAdapter.getDatas()) {
                        if (!CheckUtils.isHttp(productRelImgBean.getCameraImg())){
                            photoCount=photoCount+1;
                        }
                    }
                    setPhotoResult(photoCount);
                    finish();
                    return;
                }
                mvpPresenter.qiniutoken();
                break;
            case R.id.img_camera:
                if (mCameraPhotoAdapter.getDatas().size()==10){
                    T.show(getResources().getString(R.string.maximum_ten));
                    return;
                }
                if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
//                    T.show("sorry,camera open failed");
                    showError();
                    return;
                }
                String picPath = photoPath + System.currentTimeMillis()
                        + UVCCameraHelper.SUFFIX_JPEG;
                mCameraHelper.capturePicture(picPath,(path)-> {
                    playCallSounds();
                    compressWithLs(picPath);
                });
                break;

            case   R.id.back_btn:
                int    photoCount=0;
                for (ProductRelImgBean productRelImgBean : mCameraPhotoAdapter.getDatas()) {
                    if (!CheckUtils.isHttp(productRelImgBean.getCameraImg())){
                        photoCount=photoCount+1;
                    }
                }
                setPhotoResult(photoCount);
                finish();
                break;
        }
    }

    /**
     *
     * @param token  七牛token
     */
    @Override
    public void loadQiLitoken(String token) {
        if (this.mUploadUtils== null) {
            this.mUploadUtils = new UploadUtils();
        }
        mUploadUtils.startImageUpload(this,token,uploadData,mOnOSSFileUpload);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSoundPool!=null){  mSoundPool.release();  }
        if (mCameraHelper != null) {
            mCameraHelper.release();
        }
    }

    private UploadUtils.OnOSSFileUploadFinish mOnOSSFileUpload= new UploadUtils.OnOSSFileUploadFinish() {
        @Override
        public void OnUploadFinish(String image, String video, String videoImage) {
            L.i("image="+image);
            mvpPresenter.addphotoOrder(orderProId,image);

        }
    };
    @Override
    public void loadFail(String message) {
        T.show(message);
    }

    @Override
    public void addphotoSucceed( ) {
        FileUtils.deleteAllInDir(getPhotoSavePath());
        FileUtils.deleteAllInDir(getPath());
        setPhotoResult(mCameraPhotoAdapter.getDatas().size());
    }

    private void setPhotoResult(int  photoCount ) {
        Intent   mIntent=new Intent();
        mIntent.putExtra(ARG_PARAM1,orderProId);
        mIntent.putExtra(ARG_PARAM2,photoCount);
        setResult(RESULT_OK,mIntent);
        finish();
    }

    /**
     *
     * @param item  删除标识
     *
     */
    @Override
    public void deletePhoto(ProductRelImgBean item ) {
        T.show("删除成功");
        mCameraPhotoAdapter.getDatas().remove(item);
        mCameraPhotoAdapter.notifyDataSetChanged();
    }

    @Override
    public USBMonitor getUSBMonitor() {
        return mCameraHelper.getUSBMonitor();
    }

    @Override
    public void onDialogResult(boolean canceled) {
        if (canceled) {
            T.show("取消操作");
        }
    }

    @Override
    public void onSurfaceCreated(CameraViewInterface view, Surface surface) {
        if (!isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.startPreview(mUVCCameraView);
            isPreview = true;
        }
    }

    @Override
    public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height) {

    }

    @Override
    public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {
        if (isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.stopPreview();
            isPreview = false;
        }
    }

    private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
        @Override
        public void onAttachDev(UsbDevice device) {
            if (mCameraHelper == null || mCameraHelper.getUsbDeviceCount() == 0) {
               showError();
                return;
            }
            // request open permission
            if (!isRequest) {
                isRequest = true;
                if (mCameraHelper != null) {
                    mCameraHelper.requestPermission(0);
                }
            }
        }

        @Override
        public void onDettachDev(UsbDevice device) {
            // close camera
            if (isRequest) {
                isRequest = false;
                mCameraHelper.closeCamera();
//                T.show(device.getDeviceName() + " is out");
            }
        }

        @Override
        public void onConnectDev(UsbDevice device, boolean isConnected) {
            if (!isConnected) {
//                T.show("fail to connect,please check resolution params");
                isPreview = false;
            } else {
                isPreview = true;
                T.show(getResources().getString(R.string.connected_camera));
            }
        }

        @Override
        public void onDisConnectDev(UsbDevice device) {
            //T.show("disconnecting");
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        // step.2 register USB event broadcast
        if (mCameraHelper != null) {
            mCameraHelper.registerUSB();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // step.3 unregister USB event broadcast
        if (mCameraHelper != null) {
            mCameraHelper.unregisterUSB();
        }
    }

    private AlertDialog mDialog;
    private void showResolutionListDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(CameraSunMiActivity.this);
        View rootView = LayoutInflater.from(CameraSunMiActivity.this).inflate(R.layout.layout_dialog_list, null);
        ListView listView = (ListView) rootView.findViewById(R.id.listview_dialog);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(CameraSunMiActivity.this, android.R.layout.simple_list_item_1, getResolutionList());
        if (adapter != null) {
            listView.setAdapter(adapter);
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (mCameraHelper == null || !mCameraHelper.isCameraOpened())
                    return;
                final String resolution = (String) adapterView.getItemAtPosition(position);
                String[] tmp = resolution.split("x");
                if (tmp != null && tmp.length >= 2) {
                    int widht = Integer.valueOf(tmp[0]);
                    int height = Integer.valueOf(tmp[1]);
                    mCameraHelper.updateResolution(widht, height);
                }
                mDialog.dismiss();
            }
        });

        builder.setView(rootView);
        mDialog = builder.create();
        mDialog.show();
    }

    // example: {640x480,320x240,etc}
    private List<String> getResolutionList() {
        List<Size> list = mCameraHelper.getSupportedPreviewSizes();
        List<String> resolutions = null;
        if (list != null && list.size() != 0) {
            resolutions = new ArrayList<>();
            for (Size size : list) {
                if (size != null) {
                    resolutions.add(size.width + "x" + size.height);
                }
            }
        }
        return resolutions;
    }

}
